package com.hxd.otc.module.wallet.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.wallet.contract.CoinRechargeContrac;
import com.hxd.otc.module.wallet.presenter.CoinRechargePresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.other.UMengSharePicker;
import com.hxd.otc.utils.AddressUtil;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BottomView;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.lang.ref.SoftReference;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/5 18:03
 * 描  述 :  充值
 */
public class CoinRechargeActivity extends PermissionActivity<CoinRechargePresenter> implements CoinRechargeContrac.View {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.tv_address_tips)
    TextView tvAddressTips;
    @BindView(R.id.iv_wallet_address_qr)
    ImageView ivWalletAddressQr;
    @BindView(R.id.tv_wallet_address)
    TextView tvWalletAddress;
    @BindView(R.id.tv_copy_address)
    TextView tvCopyAddress;
    @BindView(R.id.tv_share_address)
    TextView tvShareAddress;
    @BindView(R.id.tv_rechareg_tips1)
    TextView tvRecharegTips1;

    private Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

    private static String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private BottomView bottomView;
    String coinType,coinId;
    private String mAddress;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_coin_recharge;
    }

    @Override
    protected void initView() {
        coinType = getIntent().getExtras().getString("coinType");
        coinId = getIntent().getExtras().getString("coinId");
        //底部分享界面
        bottomView = new BottomView(this, R.layout.view_wallet_address_share);
        bottomView.setCancelable(true);

    }

    public String getAddress() {
        if (TextUtils.isEmpty(mAddress) ){
            mPresenter.getRechargeCoinAddress(coinId);
            showToast(getString(R.string.get_coin_address_fail_and_retry_get));
            return "";
        }
        return mAddress;
    }

    @Override
    protected void initData() {

        tvAddressTips.setText(String.format(getString(R.string.wallet_recharge_address_tips), coinType));
        titleBar.getTitle().setText(coinType);

        //充值文字提示
        tvRecharegTips1.setText(Html.fromHtml(String.format(getString(R.string.wallet_recharge_tips1), "<font color='#417FDB'>" + coinType + "</font>")));
        mPresenter.getRechargeCoinAddress(coinId);
    }

    @Override
    protected void initEvent() {

        //保存图片
        titleBar.getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });
        //二维码图片
        ivWalletAddressQr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //复制地址
        tvCopyAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String address = getAddress();
                if (TextUtils.isEmpty(address))return;
                AddressUtil.copyAddress(CoinRechargeActivity.this, getAddress(), ResourceUtil.getString(R.string.wallet_toast_address_copy_success));
            }
        });
        //分享地址
        tvShareAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.show();
            }
        });
        //微信分享
        bottomView.findViewById(R.id.tv_share_wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(getAddress())) {
                    new UMengSharePicker.Builder().isCustomShare(true).setPlatforms(SHARE_MEDIA.WEIXIN)
                            .builder(CoinRechargeActivity.this).shareText(getAddress());
                }
                bottomView.dismiss();
                //SuccessDialog dialog = new SuccessDialog(CoinRechargeActivity.this,getString(R.string.wallet_toast_address_share_success));
                //dialog.show();
            }
        });

        //qq分享
        bottomView.findViewById(R.id.tv_share_qq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(getAddress())) {
                    new UMengSharePicker.Builder().isCustomShare(true).setPlatforms(SHARE_MEDIA.QQ)
                            .builder(CoinRechargeActivity.this).shareImage(getBitmapByString(getAddress()));
                }
                bottomView.dismiss();
            }
        });
        //短信分享
        bottomView.findViewById(R.id.tv_share_msm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(getAddress())) {
                    UIUtils.sendMessage(CoinRechargeActivity.this, getAddress());
                }
                bottomView.dismiss();
            }
        });
    }

    @Override
    protected CoinRechargePresenter createPresenter() {
        return new CoinRechargePresenter(this);
    }


    private void requestPermission() {
        super.requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                if (permissions.length == allowPermissions.size()) {
                    //如果是空地址不作处理
                    if (TextUtils.isEmpty(getAddress())) {
                        return;
                    }
                    new Handler().post(runnable);
                }
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                WalletDialogTipsUtil.showExternalTipsDialog(CoinRechargeActivity.this);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                WalletDialogTipsUtil.showExternalTipsDialog(CoinRechargeActivity.this);
            }

            @Override
            public void onLowVersion() {
                //如果是空地址不作处理
                if (TextUtils.isEmpty(getAddress())) {
                    return;
                }
                new Handler().post(runnable);
            }
        }, permissions);
    }


    Bitmap saveBitmap = null;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            viewSaveToImage();
        }
    };

    private void viewSaveToImage() {
        if (saveBitmap != null && !saveBitmap.isRecycled()) {
            saveBitmap.recycle();
            saveBitmap = null;
        }
        saveBitmap = createSaveQRBitmap(getBitmapByString(getAddress()));
        if (saveBitmap != null) {
            onShowLoading();
            AddressUtil.saveAddress(saveBitmap, coinType + DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss"),
                    new AddressUtil.SaveAddressListener() {
                        @Override
                        public void fail(String str) {
                            onHideLoading();
                            showToast(str);
                        }

                        @Override
                        public void success(String str) {
                            onHideLoading();
                            showToast(getString(R.string.save_success));
//                            WalletDialogTipsUtil.showTipsDialog(CoinRechargeActivity.this,
//                                    getString(R.string.wallet_toast_address_image_save_success),
//                                    str);
                        }
                    });
        }
    }

    /**
     * 保存二维码图片
     */
    private Bitmap createSaveQRBitmap(Bitmap qrBitmap) {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
        View view = LayoutInflater.from(this).inflate(R.layout.view_wallet_qr_code, null, false);
        // 整个View的大小 参数是左上角 和右下角的坐标
        view.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(DensityUtil.dp2px(478), View.MeasureSpec.AT_MOST);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        ImageView qr = view.findViewById(R.id.iv_save_qr_address);
        qr.setImageBitmap(qrBitmap);
        TextView tv_name = view.findViewById(R.id.tv_save_qr_user_name);
        tv_name.setText(String.format(getResources().getString(R.string.wallet_my_wallet_address_tips), UserHelper.getNickName(), coinType));
        return loadBitmapFromView(view);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    //显示二维码地址
    private void setQrCodeAddress(String address) {
        mAddress = address;
        ivWalletAddressQr.setImageBitmap(getBitmapByString(address));
        tvWalletAddress.setText(address);
    }

    public Bitmap getBitmapByString(String str) {
        // 从缓存中取软引用的Bitmap对象
        SoftReference<Bitmap> softBitmap = imageCache.get(str);
        // 判断是否存在软引用
        if (softBitmap == null) {
            return addBitmapToCache(str);
        } else {
            // 取出Bitmap对象，如果由于内存不足Bitmap被回收，将取得空
            Bitmap bitmap = softBitmap.get();
            if (bitmap == null) {
                return addBitmapToCache(str);
            } else {
                return bitmap;
            }

        }
    }

    public Bitmap addBitmapToCache(String str) {
        // 强引用的Bitmap对象
        Bitmap bitmap = CodeUtils.createImage(str, DensityUtil.dp2px(213), DensityUtil.dp2px(213), null);
        // 软引用的Bitmap对象
        SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
        // 添加该对象到Map中使其缓存
        imageCache.put(str, softBitmap);
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (String key : imageCache.keySet()) {
            SoftReference<Bitmap> softBitmap = imageCache.get(key);
            if (softBitmap != null) {
                Bitmap bitmap = softBitmap.get();
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
        if (saveBitmap != null && !saveBitmap.isRecycled()) {
            saveBitmap.recycle();
            saveBitmap = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSuccedd(String address) {
        mAddress = address;
        setQrCodeAddress(mAddress);
    }
}